#include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/i2c_master.h"
#include "read_nfc_data.h"
#include <string.h>

// 在文件开头添加NTAG相关定义
#define PICC_CMD_READ_NTAG          0x30    // NTAG读页面命令
#define PICC_CMD_WRITE_NTAG         0xA2    // NTAG写页面命令
#define PICC_CMD_GET_VERSION        0x60    // 获取版本信息

// NTAG213参数
#define NTAG213_USER_START_PAGE     4       // 用户数据起始页
#define NTAG213_PAGE_SIZE           4       // 每页4字节
#define NTAG213_PAGES_PER_BLOCK     4       // 4页相当于16字节

// 全局变量存储卡片类型
static card_type_t g_card_type = CARD_TYPE_UNKNOWN;

static const char *TAG = "RC522_NFC_DATA";

#define I2C_MASTER_SCL_IO           23       
#define I2C_MASTER_SDA_IO           22       
#define I2C_MASTER_NUM              I2C_NUM_0                   
#define I2C_MASTER_FREQ_HZ          400000 
#define I2C_MASTER_TIMEOUT_MS       1000

// 常见的RC522 I2C地址
#define RC522_I2C_ADDRESS           0x28

// RC522寄存器地址
#define RC522_REG_COMMAND           0x01
#define RC522_REG_COM_I_EN          0x02
#define RC522_REG_DIV_I_EN          0x03
#define RC522_REG_COM_IRQ           0x04
#define RC522_REG_DIV_IRQ           0x05
#define RC522_REG_ERROR             0x06
#define RC522_REG_STATUS1           0x07
#define RC522_REG_STATUS2           0x08
#define RC522_REG_FIFO_DATA         0x09
#define RC522_REG_FIFO_LEVEL        0x0A
#define RC522_REG_WATER_LEVEL       0x0B
#define RC522_REG_CONTROL           0x0C
#define RC522_REG_BIT_FRAMING       0x0D
#define RC522_REG_COLL              0x0E
#define RC522_REG_MODE              0x11
#define RC522_REG_TX_MODE           0x12
#define RC522_REG_RX_MODE           0x13
#define RC522_REG_TX_CONTROL        0x14
#define RC522_REG_TX_AUTO           0x15
#define RC522_REG_TX_SEL            0x16
#define RC522_REG_RX_SEL            0x17
#define RC522_REG_RX_THRESHOLD      0x18
#define RC522_REG_DEMOD             0x19
#define RC522_REG_MF_TX             0x1C
#define RC522_REG_MF_RX             0x1D
#define RC522_REG_CRC_RESULT_M      0x21
#define RC522_REG_CRC_RESULT_L      0x22
#define RC522_REG_VERSION           0x37

// RC522命令
#define RC522_CMD_IDLE              0x00
#define RC522_CMD_MEM               0x01
#define RC522_CMD_GENERATE_RANDOM_ID 0x02
#define RC522_CMD_CALC_CRC          0x03
#define RC522_CMD_TRANSMIT          0x04
#define RC522_CMD_NO_CMD_CHANGE     0x07
#define RC522_CMD_RECEIVE           0x08
#define RC522_CMD_TRANSCEIVE        0x0C
#define RC522_CMD_MF_AUTHENT        0x0E
#define RC522_CMD_SOFT_RESET        0x0F

// PICC命令
#define PICC_REQIDL                 0x26    // 请求空闲卡片
#define PICC_REQALL                 0x52    // 请求所有卡片
#define PICC_ANTICOLL               0x93    // 防冲突
#define PICC_SELECTTAG              0x93    // 选择卡片
#define PICC_AUTHENT1A              0x60    // 验证A密钥
#define PICC_AUTHENT1B              0x61    // 验证B密钥
#define PICC_READ                   0x30    // 读块
#define PICC_WRITE                  0xA0    // 写块
#define PICC_DECREMENT              0xC0    // 扣款
#define PICC_INCREMENT              0xC1    // 充值
#define PICC_RESTORE                0xC2    // 调块数据到缓冲区
#define PICC_TRANSFER               0xB0    // 保存缓冲区中数据
#define PICC_HALT                   0x50    // 休眠

// 返回状态
#define MI_OK                       0
#define MI_NOTAGERR                 1
#define MI_ERR                      2

// NFC数据相关定义
#define DATA_SECTOR                 1       // 使用扇区1存储数据
#define DATA_BLOCK                  1       // 扇区1的块1（绝对块号4）
#define BLOCK_SIZE                  16      // 每块16字节
#define DEFAULT_KEY                 {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}  // 默认密钥


static i2c_master_bus_handle_t bus_handle;
static i2c_master_dev_handle_t dev_handle;

// 全局变量存储最后读取的mount_point
static uint32_t g_last_mount_point = 0;  // 默认挂点为1
static bool g_data_valid = false;

static uint32_t g_last_nfc_read_time = 0;  // 最后一次成功读取NFC的时间


// 外部访问接口
uint32_t get_nfc_mount_point(void) {
    return g_last_mount_point;
}

bool is_nfc_data_valid(void) {
    if (!g_data_valid) {
        return false;
    }
    
    // 检查数据是否超时
    uint32_t current_time = esp_log_timestamp();
    if (current_time - g_last_nfc_read_time > NFC_DATA_TIMEOUT_MS) {
        g_data_valid = false;
        ESP_LOGI(TAG, "NFC数据超时，设置为无效");
        return false;
    }
    
    return true;
}
/**
 * @brief 读取RC522寄存器
 */
esp_err_t rc522_read_register(uint8_t reg_addr, uint8_t *data, size_t len)
{
    return i2c_master_transmit_receive(dev_handle, &reg_addr, 1, data, len, I2C_MASTER_TIMEOUT_MS);
}

/**
 * @brief 写入RC522寄存器
 */
static esp_err_t rc522_write_register(uint8_t reg_addr, uint8_t data)
{
    uint8_t write_buf[2] = {reg_addr, data};
    return i2c_master_transmit(dev_handle, write_buf, sizeof(write_buf), I2C_MASTER_TIMEOUT_MS);
}

/**
 * @brief 设置RC522寄存器的位
 */
static esp_err_t rc522_set_register_bit_mask(uint8_t reg_addr, uint8_t mask)
{
    uint8_t current_value;
    esp_err_t ret = rc522_read_register(reg_addr, &current_value, 1);
    if (ret != ESP_OK) {
        return ret;
    }
    return rc522_write_register(reg_addr, current_value | mask);
}

/**
 * @brief 清除RC522寄存器的位
 */
static esp_err_t rc522_clear_register_bit_mask(uint8_t reg_addr, uint8_t mask)
{
    uint8_t current_value;
    esp_err_t ret = rc522_read_register(reg_addr, &current_value, 1);
    if (ret != ESP_OK) {
        return ret;
    }
    return rc522_write_register(reg_addr, current_value & (~mask));
}

/**
 * @brief 重置RC522状态和清理内部缓冲区
 */
static void rc522_reset_state(void)
{
    // 清空FIFO缓冲区
    rc522_set_register_bit_mask(RC522_REG_FIFO_LEVEL, 0x80);
    
    // 清除所有中断标志
    rc522_write_register(RC522_REG_COM_IRQ, 0x7F);
    rc522_write_register(RC522_REG_DIV_IRQ, 0x7F);
    
    // 停止所有命令
    rc522_write_register(RC522_REG_COMMAND, RC522_CMD_IDLE);
    
    // 清除认证状态
    rc522_clear_register_bit_mask(RC522_REG_STATUS2, 0x08);
    
    // 重置位帧寄存器
    rc522_write_register(RC522_REG_BIT_FRAMING, 0x00);
    
    // 小延迟确保状态清除
    vTaskDelay(pdMS_TO_TICKS(10));
}


/**
 * @brief RC522与卡片通信
 */
static uint8_t rc522_to_card(uint8_t command, uint8_t *send_data, uint8_t send_len, uint8_t *back_data, uint16_t *back_len)
{
    uint8_t status = MI_ERR;
    uint8_t irq_en = 0x00;
    uint8_t wait_irq = 0x00;
    uint8_t last_bits;
    uint8_t n;
    uint16_t i;
    
    switch (command) {
        case RC522_CMD_MF_AUTHENT:
            irq_en = 0x12;
            wait_irq = 0x10;
            break;
        case RC522_CMD_TRANSCEIVE:
            irq_en = 0x77;
            wait_irq = 0x30;
            break;
        default:
            break;
    }
    
    rc522_write_register(RC522_REG_COM_I_EN, irq_en | 0x80);
    rc522_clear_register_bit_mask(RC522_REG_COM_IRQ, 0x80);
    rc522_set_register_bit_mask(RC522_REG_FIFO_LEVEL, 0x80);
    
    rc522_write_register(RC522_REG_COMMAND, RC522_CMD_IDLE);
    
    // 写数据到FIFO
    for (i = 0; i < send_len; i++) {
        rc522_write_register(RC522_REG_FIFO_DATA, send_data[i]);
    }
    
    // 执行命令
    rc522_write_register(RC522_REG_COMMAND, command);
    if (command == RC522_CMD_TRANSCEIVE) {
        rc522_set_register_bit_mask(RC522_REG_BIT_FRAMING, 0x80);
    }
    
    // 等待接收数据完成
    i = 2000;
    do {
        uint8_t com_irq_reg;
        rc522_read_register(RC522_REG_COM_IRQ, &com_irq_reg, 1);
        n = com_irq_reg;
        i--;
    } while ((i != 0) && !(n & 0x01) && !(n & wait_irq));
    
    rc522_clear_register_bit_mask(RC522_REG_BIT_FRAMING, 0x80);
    
    if (i != 0) {
        uint8_t error_reg;
        rc522_read_register(RC522_REG_ERROR, &error_reg, 1);
        if (!(error_reg & 0x1B)) {
            status = MI_OK;
            if (n & irq_en & 0x01) {
                status = MI_NOTAGERR;
            }
            
            if (command == RC522_CMD_TRANSCEIVE) {
                uint8_t fifo_level;
                rc522_read_register(RC522_REG_FIFO_LEVEL, &fifo_level, 1);
                n = fifo_level;
                
                uint8_t control_reg;
                rc522_read_register(RC522_REG_CONTROL, &control_reg, 1);
                last_bits = control_reg & 0x07;
                
                if (last_bits) {
                    *back_len = (n - 1) * 8 + last_bits;
                } else {
                    *back_len = n * 8;
                }
                
                if (n == 0) {
                    n = 1;
                }
                if (n > 16) {
                    n = 16;
                }
                
                // 从FIFO读取接收到的数据
                for (i = 0; i < n; i++) {
                    rc522_read_register(RC522_REG_FIFO_DATA, &back_data[i], 1);
                }
            }
        } else {
            status = MI_ERR;
        }
    }
    
    return status;
}

/**
 * @brief 寻卡
 */
static uint8_t rc522_request(uint8_t req_mode, uint8_t *tag_type)
{
    uint8_t status;
    uint16_t back_bits;
    
    rc522_write_register(RC522_REG_BIT_FRAMING, 0x07);
    
    tag_type[0] = req_mode;
    status = rc522_to_card(RC522_CMD_TRANSCEIVE, tag_type, 1, tag_type, &back_bits);
    
    if ((status != MI_OK) || (back_bits != 0x10)) {
        status = MI_ERR;
    }
    
    return status;
}

/**
 * @brief 防冲突，读取卡片序列号
 */
static uint8_t rc522_anticoll(uint8_t *serial_num)
{
    uint8_t status;
    uint8_t i;
    uint8_t serial_num_check = 0;
    uint16_t unlen;
    
    rc522_write_register(RC522_REG_BIT_FRAMING, 0x00);
    
    serial_num[0] = PICC_ANTICOLL;
    serial_num[1] = 0x20;
    status = rc522_to_card(RC522_CMD_TRANSCEIVE, serial_num, 2, serial_num, &unlen);
    
    if (status == MI_OK) {
        // 校验卡序列号
        for (i = 0; i < 4; i++) {
            serial_num_check ^= serial_num[i];
        }
        if (serial_num_check != serial_num[i]) {
            status = MI_ERR;
        }
    }
    
    return status;
}

/**
 * @brief 用RC522计算CRC16
 */
static void rc522_calculate_crc(uint8_t *in_data, uint8_t len, uint8_t *out_data)
{
    uint8_t i, n;
    
    rc522_clear_register_bit_mask(RC522_REG_DIV_IRQ, 0x04);
    rc522_set_register_bit_mask(RC522_REG_FIFO_LEVEL, 0x80);
    
    // 写数据到FIFO
    for (i = 0; i < len; i++) {
        rc522_write_register(RC522_REG_FIFO_DATA, *(in_data + i));
    }
    rc522_write_register(RC522_REG_COMMAND, RC522_CMD_CALC_CRC);
    
    // 等待CRC计算完成
    i = 0xFF;
    do {
        uint8_t div_irq;
        rc522_read_register(RC522_REG_DIV_IRQ, &div_irq, 1);
        n = div_irq;
        i--;
    } while ((i != 0) && !(n & 0x04));
    
    // 读取CRC计算结果
    rc522_read_register(RC522_REG_CRC_RESULT_L, &out_data[0], 1);
    rc522_read_register(RC522_REG_CRC_RESULT_M, &out_data[1], 1);
}

/**
 * @brief 选择卡片，读取卡片容量
 */
static uint8_t rc522_select_tag(uint8_t *serial_num)
{
    uint8_t status;
    uint8_t size;
    uint16_t recv_bits;
    uint8_t buffer[9];
    
    buffer[0] = PICC_SELECTTAG;
    buffer[1] = 0x70;
    for (uint8_t i = 0; i < 5; i++) {
        buffer[i + 2] = *(serial_num + i);
    }
    rc522_calculate_crc(buffer, 7, &buffer[7]);
    status = rc522_to_card(RC522_CMD_TRANSCEIVE, buffer, 9, buffer, &recv_bits);
    
    if ((status == MI_OK) && (recv_bits == 0x18)) {
        size = buffer[0];
    } else {
        size = 0;
    }
    
    return size;
}

/**
 * @brief 选择卡片（改进版，返回SAK值）
 */
static uint8_t rc522_select_tag_improved(uint8_t *serial_num, uint8_t *sak)
{
    uint8_t status;
    uint16_t recv_bits;
    uint8_t buffer[9];
    
    buffer[0] = PICC_SELECTTAG;
    buffer[1] = 0x70;
    for (uint8_t i = 0; i < 5; i++) {
        buffer[i + 2] = *(serial_num + i);
    }
    rc522_calculate_crc(buffer, 7, &buffer[7]);
    status = rc522_to_card(RC522_CMD_TRANSCEIVE, buffer, 9, buffer, &recv_bits);
    
    if ((status == MI_OK) && (recv_bits == 0x18)) {
        *sak = buffer[0];  // SAK值
        return buffer[0];
    }
    
    return 0;
}

/**
 * @brief NTAG专用的简化通信函数
 */
static uint8_t ntag_transceive(uint8_t *send_data, uint8_t send_len, uint8_t *recv_data, uint16_t *recv_len)
{
    uint8_t status;
    
    // 清除所有中断标志
    rc522_write_register(RC522_REG_COM_IRQ, 0x7F);
    
    // 清空FIFO
    rc522_set_register_bit_mask(RC522_REG_FIFO_LEVEL, 0x80);
    
    // 设置为空闲状态
    rc522_write_register(RC522_REG_COMMAND, RC522_CMD_IDLE);
    
    // 写入数据到FIFO
    for (uint8_t i = 0; i < send_len; i++) {
        rc522_write_register(RC522_REG_FIFO_DATA, send_data[i]);
    }
    
    // 启动传输
    rc522_write_register(RC522_REG_COMMAND, RC522_CMD_TRANSCEIVE);
    rc522_set_register_bit_mask(RC522_REG_BIT_FRAMING, 0x80);
    
    // 等待完成
    uint16_t timeout = 1000;
    uint8_t irq_reg;
    do {
        rc522_read_register(RC522_REG_COM_IRQ, &irq_reg, 1);
        vTaskDelay(pdMS_TO_TICKS(1));
        timeout--;
    } while (!(irq_reg & 0x30) && timeout > 0);
    
    rc522_clear_register_bit_mask(RC522_REG_BIT_FRAMING, 0x80);
    
    if (timeout == 0) {
        ESP_LOGE(TAG, "NTAG通信超时");
        return MI_ERR;
    }
    
    // 检查错误
    uint8_t error_reg;
    rc522_read_register(RC522_REG_ERROR, &error_reg, 1);
    if (error_reg & 0x13) {  // ParityErr, ProtocolErr, BufferOvfl
        ESP_LOGE(TAG, "NTAG通信错误: 0x%02X", error_reg);
        return MI_ERR;
    }
    
    // 读取数据
    uint8_t fifo_level;
    rc522_read_register(RC522_REG_FIFO_LEVEL, &fifo_level, 1);
    
    if (fifo_level > 0) {
        for (uint8_t i = 0; i < fifo_level && i < 16; i++) {
            rc522_read_register(RC522_REG_FIFO_DATA, &recv_data[i], 1);
        }
        *recv_len = fifo_level * 8;
        return MI_OK;
    }
    
    return MI_ERR;
}

/**
 * @brief 识别卡片类型
 */
static card_type_t identify_card_type(uint8_t *atqa, uint8_t sak)
{
    // 根据SAK值判断
    // MIFARE Classic 1K: SAK = 0x08
    // MIFARE Classic 4K: SAK = 0x18
    // NTAG213/215/216: SAK = 0x00
    
    ESP_LOGI(TAG, "检测到卡片 (SAK: 0x%02X)", sak);

    if (sak == 0x08 || sak == 0x18) {
        ESP_LOGI(TAG, "检测到MIFARE Classic卡片 (SAK: 0x%02X)", sak);
        return CARD_TYPE_MIFARE_CLASSIC;
    } else if (sak == 0x04) {
        // NTAG系列的SAK都是0x00，需要进一步识别
        ESP_LOGI(TAG, "检测到NTAG系列标签 (SAK: 0x%02X)", sak);
        // 可以通过GET_VERSION命令进一步识别具体型号
        return CARD_TYPE_NTAG213;  // 默认为NTAG213
    }
    
    return CARD_TYPE_UNKNOWN;
}

/**
 * @brief 改进的NTAG读页面函数
 */
static uint8_t ntag_read_page(uint8_t page_addr, uint8_t *recv_data)
{
    uint8_t cmd_buf[4];
    uint16_t recv_len;
    
    ESP_LOGI(TAG, "读取NTAG页面%d", page_addr);
    
    cmd_buf[0] = 0x30;  // READ命令
    cmd_buf[1] = page_addr;
    rc522_calculate_crc(cmd_buf, 2, &cmd_buf[2]);
    
    // 使用NTAG专用通信函数
    uint8_t status = ntag_transceive(cmd_buf, 4, recv_data, &recv_len);
    
    if (status == MI_OK && recv_len >= 128) {  // 16字节 = 128位
        ESP_LOGI(TAG, "成功读取页面%d", page_addr);
        ESP_LOG_BUFFER_HEX(TAG, recv_data, 16);
        return MI_OK;
    }
    
    ESP_LOGE(TAG, "读取页面%d失败: status=%d, len=%d", page_addr, status, recv_len);
    return MI_ERR;
}

/**
 * @brief 读取NTAG数据（16字节，相当于4个页面）
 */
static uint8_t ntag_read_block_data(uint8_t start_page, uint8_t *block_data)
{
    uint8_t status;
    uint8_t page_data[16];  // NTAG读命令返回4个页面（16字节）
    
    // NTAG的READ命令一次返回4个页面
    status = ntag_read_page(start_page, page_data);
    if (status != MI_OK) {
        return MI_ERR;
    }
    
    // 复制16字节数据
    memcpy(block_data, page_data, 16);
    
    ESP_LOGI(TAG, "成功读取NTAG页面 %d-%d", start_page, start_page + 3);
    ESP_LOG_BUFFER_HEX(TAG, block_data, 16);
    
    return MI_OK;
}

/**
 * @brief MIFARE认证
 */
static uint8_t rc522_auth(uint8_t auth_mode, uint8_t block_addr, uint8_t *key, uint8_t *serial_num)
{
    uint8_t status;
    uint16_t recv_bits;
    uint8_t i;
    uint8_t buff[12];
    
    // 验证指令 + 块地址 + 密钥 + 卡序列号前4字节
    buff[0] = auth_mode;
    buff[1] = block_addr;
    for (i = 0; i < 6; i++) {
        buff[i + 2] = *(key + i);
    }
    for (i = 0; i < 4; i++) {
        buff[i + 8] = *(serial_num + i);
    }
    
    status = rc522_to_card(RC522_CMD_MF_AUTHENT, buff, 12, buff, &recv_bits);
    
    if ((status != MI_OK) || (!(rc522_read_register(RC522_REG_STATUS2, &i, 1) == ESP_OK && (i & 0x08)))) {
        status = MI_ERR;
    }
    
    return status;
}

/**
 * @brief 读取块数据
 */
static uint8_t rc522_read_block(uint8_t block_addr, uint8_t *recv_data)
{
    uint8_t status;
    uint16_t unlen;
    
    recv_data[0] = PICC_READ;
    recv_data[1] = block_addr;
    rc522_calculate_crc(recv_data, 2, &recv_data[2]);
    status = rc522_to_card(RC522_CMD_TRANSCEIVE, recv_data, 4, recv_data, &unlen);
    
    if ((status != MI_OK) || (unlen != 0x90)) {
        status = MI_ERR;
    }
    
    return status;
}

/**
 * @brief 写入块数据
 */
uint8_t rc522_write_block(uint8_t block_addr, uint8_t *write_data)
{
    uint8_t status;
    uint16_t recv_bits;
    uint8_t i;
    uint8_t buff[18];
    
    buff[0] = PICC_WRITE;
    buff[1] = block_addr;
    rc522_calculate_crc(buff, 2, &buff[2]);
    status = rc522_to_card(RC522_CMD_TRANSCEIVE, buff, 4, buff, &recv_bits);
    
    if ((status != MI_OK) || (recv_bits != 4) || ((buff[0] & 0x0F) != 0x0A)) {
        status = MI_ERR;
    }
    
    if (status == MI_OK) {
        // 写入16字节数据
        for (i = 0; i < 16; i++) {
            buff[i] = *(write_data + i);
        }
        rc522_calculate_crc(buff, 16, &buff[16]);
        status = rc522_to_card(RC522_CMD_TRANSCEIVE, buff, 18, buff, &recv_bits);
        
        if ((status != MI_OK) || (recv_bits != 4) || ((buff[0] & 0x0F) != 0x0A)) {
            status = MI_ERR;
        }
    }
    
    return status;
}

/**
 * @brief 停止通信
 */
void rc522_halt(void)
{
    uint8_t buff[4];
    uint16_t unlen;
    
    // 发送HALT命令
    buff[0] = PICC_HALT;
    buff[1] = 0;
    rc522_calculate_crc(buff, 2, &buff[2]);
    
    rc522_to_card(RC522_CMD_TRANSCEIVE, buff, 4, buff, &unlen);
    
    // 额外延迟确保卡片响应HALT命令
    vTaskDelay(pdMS_TO_TICKS(50));
    
    // 清除认证状态
    rc522_clear_register_bit_mask(RC522_REG_STATUS2, 0x08);
}

/**
 * @brief 初始化I2C总线和RC522设备
 */
esp_err_t rc522_i2c_init(void)
{
    // 配置I2C总线
    i2c_master_bus_config_t bus_config = {
        .i2c_port = I2C_MASTER_NUM,
        .sda_io_num = I2C_MASTER_SDA_IO,
        .scl_io_num = I2C_MASTER_SCL_IO,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true,
    };
    ESP_ERROR_CHECK(i2c_new_master_bus(&bus_config, &bus_handle));

    // 配置RC522设备
    i2c_device_config_t dev_config = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = RC522_I2C_ADDRESS,
        .scl_speed_hz = I2C_MASTER_FREQ_HZ,
    };
    ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_config, &dev_handle));
    
    return ESP_OK;
}

/**
 * @brief RC522软复位
 */
esp_err_t rc522_reset(void)
{
    esp_err_t ret = rc522_write_register(RC522_REG_COMMAND, RC522_CMD_SOFT_RESET);
    if (ret != ESP_OK) {
        return ret;
    }
    
    vTaskDelay(pdMS_TO_TICKS(50));
    
    uint8_t timeout = 0;
    uint8_t status;
    do {
        ret = rc522_read_register(RC522_REG_COMMAND, &status, 1);
        if (ret != ESP_OK) {
            return ret;
        }
        vTaskDelay(pdMS_TO_TICKS(10));
        timeout++;
    } while ((status & 0x10) && (timeout < 10));
    
    if (timeout >= 10) {
        ESP_LOGE(TAG, "RC522复位超时");
        return ESP_ERR_TIMEOUT;
    }
    
    return ESP_OK;
}

/**
 * @brief 初始化RC522天线
 */
esp_err_t rc522_antenna_on(void)
{
    esp_err_t ret = rc522_set_register_bit_mask(RC522_REG_TX_CONTROL, 0x03);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "开启天线失败");
        return ret;
    }
    
    ESP_LOGI(TAG, "天线已开启");
    return ESP_OK;
}

/**
 * @brief 初始化RC522为RFID模式
 */
esp_err_t rc522_init_rfid_mode(void)
{
    esp_err_t ret;
    
    ret = rc522_reset();
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "RC522复位失败");
        return ret;
    }
    
    ret = rc522_write_register(0x2A, 0x8D);
    if (ret != ESP_OK) return ret;
    
    ret = rc522_write_register(0x2B, 0x3E);
    if (ret != ESP_OK) return ret;
    
    ret = rc522_write_register(0x2D, 30);
    if (ret != ESP_OK) return ret;
    
    ret = rc522_write_register(0x2C, 0);
    if (ret != ESP_OK) return ret;
    
    ret = rc522_write_register(RC522_REG_TX_AUTO, 0x40);
    if (ret != ESP_OK) return ret;
    
    ret = rc522_write_register(RC522_REG_MODE, 0x3D);
    if (ret != ESP_OK) return ret;
    
    ret = rc522_antenna_on();
    if (ret != ESP_OK) return ret;
    
    ESP_LOGI(TAG, "RC522 RFID模式初始化完成");
    return ESP_OK;
}

/**
 * @brief 解析NFC数据
 */
static bool parse_nfc_data(uint8_t *block_data, nfc_data_t *nfc_data)
{
    // 检查数据有效性（简单校验）
    if (block_data[0] == 0x00 && block_data[1] == 0x00 && 
        block_data[2] == 0x00 && block_data[3] == 0x00) {
        return false;  // 全0数据认为无效
    }
    
    // 直接拷贝数据
    memcpy(nfc_data, block_data, sizeof(nfc_data_t));

    // 检查reserved1是否为预期值0x1234
    if (nfc_data->reserved1 != 0x1234) {
        ESP_LOGW(TAG, "数据校验失败: reserved1 = 0x%04X, 期望值 = 0x1234", nfc_data->reserved1);
        return false;
    }

    return true;
}

/**
 * @brief 读取并解析NFC卡数据
 */
// static void nfc_read_and_parse_data(void)
// {
//     uint8_t status;
//     uint8_t str[16];
//     uint8_t serial_num[5];
//     uint8_t default_key[] = DEFAULT_KEY;
//     uint8_t block_data[16];
//     nfc_data_t nfc_data;
    
//     // 开始前重置RC522状态
//     rc522_reset_state();
    
//     // 寻卡
//     status = rc522_request(PICC_REQIDL, str);
//     if (status != MI_OK) {
//         return;  // 没有检测到卡片
//     }
    
//     ESP_LOGI(TAG, "检测到NFC卡片");
    
//     // 防冲突，获取卡片序列号
//     status = rc522_anticoll(serial_num);
//     if (status != MI_OK) {
//         ESP_LOGW(TAG, "读取卡号失败");
//         goto cleanup;
//     }
    
//     ESP_LOGI(TAG, "卡UID: %02X %02X %02X %02X", 
//              serial_num[0], serial_num[1], serial_num[2], serial_num[3]);
    
//     // 选择卡片
//     uint8_t size = rc522_select_tag(serial_num);
//     if (size == 0) {
//         ESP_LOGW(TAG, "选择卡片失败");
//         goto cleanup;
//     }
    
//     // 计算绝对块号：扇区号 * 4 + 块号
//     uint8_t abs_block = DATA_SECTOR * 4 + DATA_BLOCK;
    
//     // 认证（使用A密钥）
//     status = rc522_auth(PICC_AUTHENT1A, abs_block, default_key, serial_num);
//     if (status != MI_OK) {
//         ESP_LOGW(TAG, "密钥认证失败，使用默认密钥");
//         goto cleanup;
//     }
    
//     ESP_LOGI(TAG, "密钥认证成功");
    
//     // 读取数据块
//     status = rc522_read_block(abs_block, block_data);
//     if (status != MI_OK) {
//         ESP_LOGW(TAG, "读取数据块失败");
//         goto cleanup;
//     }
    
//     ESP_LOGI(TAG, "成功读取数据块%d", abs_block);
//     ESP_LOG_BUFFER_HEX(TAG, block_data, BLOCK_SIZE);
    
//     // 解析数据
//     if (parse_nfc_data(block_data, &nfc_data)) {
//         g_last_mount_point = nfc_data.mount_point;
//         g_data_valid = true;
        
//         ESP_LOGI(TAG, "解析NFC数据成功:");
//         ESP_LOGI(TAG, "  挂点编号: %lu", nfc_data.mount_point);
//         ESP_LOGI(TAG, "  设备类型: %u", nfc_data.device_type);
//         ESP_LOGI(TAG, "  时间戳: %lu", nfc_data.timestamp);
//     } else {
//         ESP_LOGW(TAG, "NFC数据解析失败或数据无效");
//     }
    
// cleanup:
//     // 改进的停止通信
//     rc522_halt();
    
//     // 额外的状态重置
//     rc522_reset_state();
    
//     ESP_LOGI(TAG, "读卡操作完成，等待下次检测...");
// }

/**
 * @brief 改进的NFC数据读取函数（支持MIFARE和NTAG）
 */
static void nfc_read_and_parse_data_universal(void)
{
    uint8_t status;
    uint8_t str[16];
    uint8_t serial_num[5];
    uint8_t sak;
    uint8_t block_data[16];
    nfc_data_t nfc_data;
    
    // 开始前重置RC522状态
    rc522_reset_state();
    
    // 寻卡
    status = rc522_request(PICC_REQIDL, str);
    if (status != MI_OK) {
        return;  // 没有检测到卡片
    }
    
    ESP_LOGI(TAG, "检测到NFC卡片");
    
    // 防冲突，获取卡片序列号
    status = rc522_anticoll(serial_num);
    if (status != MI_OK) {
        ESP_LOGW(TAG, "读取卡号失败");
        goto cleanup;
    }
    
    ESP_LOGI(TAG, "卡UID: %02X %02X %02X %02X", 
             serial_num[0], serial_num[1], serial_num[2], serial_num[3]);
    
    // 选择卡片并获取SAK
    if (rc522_select_tag_improved(serial_num, &sak) == 0) {
        ESP_LOGW(TAG, "选择卡片失败");
        goto cleanup;
    }
    
    // 识别卡片类型
    g_card_type = identify_card_type(str, sak);
    
    if (g_card_type == CARD_TYPE_MIFARE_CLASSIC) {
        // MIFARE Classic卡片处理
        uint8_t default_key[] = DEFAULT_KEY;
        uint8_t abs_block = DATA_SECTOR * 4 + DATA_BLOCK;
        
        // 认证
        status = rc522_auth(PICC_AUTHENT1A, abs_block, default_key, serial_num);
        if (status != MI_OK) {
            ESP_LOGW(TAG, "MIFARE密钥认证失败");
            goto cleanup;
        }
        
        ESP_LOGI(TAG, "MIFARE密钥认证成功");
        
        // 读取数据块
        status = rc522_read_block(abs_block, block_data);
        if (status != MI_OK) {
            ESP_LOGW(TAG, "读取MIFARE数据块失败");
            goto cleanup;
        }
        
    } else if (g_card_type == CARD_TYPE_NTAG213) {
        // NTAG213处理 - 直接读取，不需要认证
        uint8_t start_page = NTAG213_USER_START_PAGE;
        
        status = ntag_read_block_data(start_page, block_data);
        if (status != MI_OK) {
            ESP_LOGW(TAG, "读取NTAG213数据失败");
            goto cleanup;
        }
        
    } else {
        ESP_LOGW(TAG, "未知卡片类型");
        goto cleanup;
    }
    
    ESP_LOG_BUFFER_HEX(TAG, block_data, BLOCK_SIZE);
    
    // 解析数据
    if (parse_nfc_data(block_data, &nfc_data)) {
        g_last_mount_point = nfc_data.mount_point;
        g_data_valid = true;
        g_last_nfc_read_time = esp_log_timestamp();

        ESP_LOGI(TAG, "解析NFC数据成功:");
        ESP_LOGI(TAG, "  挂点编号: %lu", nfc_data.mount_point);
        ESP_LOGI(TAG, "  设备类型: %u", nfc_data.device_type);
        ESP_LOGI(TAG, "  时间戳: %lu", nfc_data.timestamp);
    } else {
        ESP_LOGW(TAG, "NFC数据解析失败或数据无效");
    }
    
cleanup:
    // rc522_halt();
    rc522_reset_state();
    ESP_LOGI(TAG, "读卡操作完成，等待下次检测...");
}


/**
 * @brief 写入NFC卡数据
 */
esp_err_t nfc_write_data(uint32_t mount_point, uint16_t device_type)
{
    uint8_t status;
    uint8_t str[16];
    uint8_t serial_num[5];
    uint8_t default_key[] = DEFAULT_KEY;
    nfc_data_t nfc_data = {0};
    
    // 准备要写入的数据
    nfc_data.mount_point = mount_point;
    nfc_data.device_type = device_type;
    nfc_data.timestamp = (uint32_t)(esp_log_timestamp() / 1000);  // 当前时间戳（秒）
    nfc_data.reserved1 = 0x1234;  // 预留字段可以设置标识
    nfc_data.reserved2 = 0x5678ABCD;
    
    ESP_LOGI(TAG, "准备写入数据:");
    ESP_LOGI(TAG, "  挂点编号: %lu", nfc_data.mount_point);
    ESP_LOGI(TAG, "  设备类型: %u", nfc_data.device_type);
    ESP_LOGI(TAG, "  时间戳: %lu", nfc_data.timestamp);
    
    // 寻卡
    status = rc522_request(PICC_REQIDL, str);
    if (status != MI_OK) {
        ESP_LOGE(TAG, "没有检测到卡片");
        return ESP_ERR_NOT_FOUND;
    }
    
    // 防冲突
    status = rc522_anticoll(serial_num);
    if (status != MI_OK) {
        ESP_LOGE(TAG, "读取卡号失败");
        return ESP_FAIL;
    }
    
    // 选择卡片
    if (rc522_select_tag(serial_num) == 0) {
        ESP_LOGE(TAG, "选择卡片失败");
        return ESP_FAIL;
    }
    
    // 计算绝对块号
    uint8_t abs_block = DATA_SECTOR * 4 + DATA_BLOCK;
    
    // 认证
    status = rc522_auth(PICC_AUTHENT1A, abs_block, default_key, serial_num);
    if (status != MI_OK) {
        ESP_LOGE(TAG, "密钥认证失败");
        rc522_halt();
        return ESP_ERR_INVALID_STATE;
    }
    
    // 写入数据
    status = rc522_write_block(abs_block, (uint8_t*)&nfc_data);
    if (status != MI_OK) {
        ESP_LOGE(TAG, "写入数据失败");
        rc522_halt();
        return ESP_FAIL;
    }
    
    ESP_LOGI(TAG, "NFC数据写入成功");
    
    // 停止通信
    rc522_halt();
    
    return ESP_OK;
}

/**
 * @brief NFC数据读取任务
 */
void nfc_read_task(void *pvParameters)
{
    ESP_LOGI(TAG, "NFC数据读取任务启动");
    
    while (1) {
        nfc_read_and_parse_data_universal();
        vTaskDelay(pdMS_TO_TICKS(1500));  // 每秒检测一次
    }
}

// void app_main(void)
// {
//     ESP_LOGI(TAG, "初始化RC522 NFC数据读取...");
    
//     // 初始化I2C
//     esp_err_t ret = rc522_i2c_init();
//     if (ret != ESP_OK) {
//         ESP_LOGE(TAG, "I2C初始化失败: %s", esp_err_to_name(ret));
//         return;
//     }
    
//     ESP_LOGI(TAG, "I2C初始化成功");
    
//     // 读取版本寄存器验证通信
//     uint8_t version;
//     ret = rc522_read_register(RC522_REG_VERSION, &version, 1);
//     if (ret == ESP_OK) {
//         ESP_LOGI(TAG, "RC522版本: 0x%02X", version);
        
//         if (version == 0x91 || version == 0x92 || version == 0x88) {
//             ESP_LOGI(TAG, "RC522检测成功！");
//         } else {
//             ESP_LOGW(TAG, "意外的版本号，但通信正常");
//         }
//     } else {
//         ESP_LOGE(TAG, "读取RC522版本失败: %s", esp_err_to_name(ret));
//         return;
//     }
    
//     // 初始化RFID模式
//     ret = rc522_init_rfid_mode();
//     if (ret != ESP_OK) {
//         ESP_LOGE(TAG, "RFID模式初始化失败: %s", esp_err_to_name(ret));
//         return;
//     }
    
//     ESP_LOGI(TAG, "RC522 NFC数据读取初始化完成");
//     ESP_LOGI(TAG, "请将NFC卡片靠近读卡器...");
    
//     // 启动NFC数据读取任务
//     xTaskCreate(nfc_read_task, "nfc_read_task", 4096, NULL, 5, NULL);
    
//     // 示例：5秒后写入测试数据（可选）
//     vTaskDelay(pdMS_TO_TICKS(5000));
//     ESP_LOGI(TAG, "5秒后将尝试写入测试数据...");
    
//     // 可以在这里调用写入函数进行测试
//     // nfc_write_data(12345, 0x0001);
// }